package com.thinksns.sociax.api;

import android.text.TextUtils;

import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.model.ModelVideo;
import com.thinksns.sociax.t4.model.VerifyDetails;
import com.thinksns.sociax.t4.model.VerifyModel;
import com.thinksns.sociax.thinksnsbase.network.ApiHttpClient;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * @author LeiYan
 * @describe
 * @date 2017/7/24
 * @contact email:907238552@qq.com
 */

public class ApiVerify {
    private final String GET_USER_VERIFY = "get_user_verify"; // 认证分类
    private final String GET_VERIFY_INFO = "verifiedInfo"; // 获取认证信息
    private final String DO_AUTHENTICATE = "doAuthenticate"; // 提交认证信息
    private final String DEL_VERIFY = "delverify"; //  注销认证信息
    private final String UPLOAD_USER_VERIFY_PIC = "uploadUserVerifyPic"; //  上传认证图片

    private static ApiVerify mVerify = new ApiVerify();

    public static ApiVerify getInstance() {
        return mVerify;
    }


    /**
     * 认证分类
     *
     * @param listener
     */
    public void getUserVerify(final ApiHttpClient.HttpResponseListener listener) {
        OkHttpUtils.get()
                .url(ApiHttpClient.getApiUrl())
                .params(getParams(Api.FindPeople.MOD_NAME, GET_USER_VERIFY))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        listener.onError(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            List<VerifyModel> resultList = new ArrayList<VerifyModel>();
                            JSONArray array = new JSONArray(response);
                            int length = array.length();
                            VerifyModel verifyModel;
                            for (int i = 0; i < length; i++) {
                                verifyModel = new VerifyModel(array.optJSONObject(i));
                                resultList.add(verifyModel);
                            }
                            listener.onSuccess(resultList);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            listener.onError(e.getMessage());
                        }

                    }
                });
    }

    /**
     * 获取认证信息
     */
    public void getVerifyInfo(final ApiHttpClient.HttpResponseListener listener) {
        OkHttpUtils.get()
                .url(ApiHttpClient.getApiUrl())
                .params(getParams(ApiUsers.MOD_NAME, GET_VERIFY_INFO))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        listener.onError(null);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (1 != jsonObject.optInt("status")) {
                                listener.onError(jsonObject.optString("msg"));
                                return;
                            }
                            VerifyDetails details = new VerifyDetails(jsonObject.optJSONObject("data"));
                            listener.onSuccess(details);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 提交认证信息
     *
     * @param verifyDetails
     * @param attachIds
     * @param callback
     */
    public void doAuthenticate(VerifyDetails verifyDetails, String attachIds, Callback callback) {
        Map map = getParams(ApiUsers.MOD_NAME, DO_AUTHENTICATE);
        map.put("usergroup_id", "" + verifyDetails.getUsergroup_id()); // 认证组ID
        if (verifyDetails.getUser_verified_category() != null) {
            map.put("verifiedCategory", verifyDetails.getUser_verified_category().getVerify_id()); // 认证类型ID
        }
        if (!TextUtils.isEmpty(verifyDetails.getCompany())) {
            map.put("company", verifyDetails.getCompany()); //机构名称
        }
        map.put("realname", verifyDetails.getRealname()); // 负责人姓名/真实姓名
        map.put("idcard", verifyDetails.getIdcard()); //身份证号码
        map.put("phone", verifyDetails.getPhone()); // 联系方式

        if (!TextUtils.isEmpty(verifyDetails.getReason())) {
            map.put("reason", verifyDetails.getReason()); // 认证补充
        }
        if (!TextUtils.isEmpty(verifyDetails.getInfo())) {
            map.put("info", verifyDetails.getInfo()); // 认证资料 (选填)
        }
        if (!TextUtils.isEmpty(attachIds)) {
            map.put("attach_ids", attachIds); // 认证附件（不止一个附件请用 | 隔开）-选填
        }
        OkHttpUtils.get()
                .url(ApiHttpClient.getApiUrl())
                .params(map)
                .build()
                .execute(callback);
    }

    /**
     * 注销认证信息
     */
    public void deleteVerify(Callback callback) {
        OkHttpUtils.get()
                .url(ApiHttpClient.getApiUrl())
                .params(getParams(ApiUsers.MOD_NAME, DEL_VERIFY))
                .build()
                .execute(callback);
    }

    /**
     * 上传认证图片
     *
     * @param pathList
     */
    public void uploadPic(List<String> pathList, Callback callback) {
        PostFormBuilder builder = OkHttpUtils.post();
        File file = null;
        for (int i = 0; i < pathList.size(); i++) {
            file = new File(pathList.get(i).replace("file://", ""));
            if (file.exists()) {
                builder.addFile("mFile" + i, file.getName(), file);
            }
        }

        builder.url(ApiHttpClient.getApiUrl())
                .addHeader("Accept-Encoding", "UTF-8")
                .params(getParams(ApiUsers.MOD_NAME, UPLOAD_USER_VERIFY_PIC))
                .build()
                .execute(callback);
    }

    public  static Map getParams(String mod, String act) {
        Map map = new HashMap();
        map.put("mod", mod);
        map.put("act", act);
        map.put("oauth_token", ApiHttpClient.TOKEN);
        map.put("oauth_token_secret", ApiHttpClient.TOKEN_SECRET);
        map.put("api_type", Api.getmApiType());
        map.put("api_version", Api.getmApiVersion());
        return map;
    }
}
